import json
import re

from django import http
from django.views import View

from apps.users.models import User
from love_home.settings.dev import logger
from love_home.utils.check_id_card import checkIdcard
from love_home.utils.qiniuyun import upload_img, deletes
from love_home.utils.response_code import RET
from love_home.utils.views import LoginRequiredJSONMixin


#  用户中心
class profileView(LoginRequiredJSONMixin, View):
    #  数据展示
    def get(self, request):
        user = request.user

        data = {
            'name': user.username,
            'avatar_url': user.avatar_url,
            'mobile': user.mobile
        }

        return http.JsonResponse({"errno": RET.OK, "errmsg": "OK", "data": data})

    #  修改用户名
    def post(self, request):

        json_dict = json.loads(request.body.decode())
        name = json_dict.get('name')

        if name is None:
            return http.JsonResponse({"errno": RET.NODATA, "errmsg": "缺少参数"})

        try:
            count = User.objects.filter(username=name).count()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({"errno": RET.DBERR, "errmsg": "修改失败"})

        if count:
            return http.JsonResponse({"errno": RET.DBERR, "errmsg": "用户名已存在"})
        try:
            request.user.username = name
            request.user.save()
        except:
            return http.JsonResponse({"errno": RET.DBERR, "errmsg": "修改失败"})
        return http.JsonResponse({"errno": RET.OK, "errmsg": "OK"})


#  修改头像
class avatarView(LoginRequiredJSONMixin, View):
    def post(self, request):
        avatar = request.FILES.get('avatar')
        if avatar is None:
            return http.JsonResponse({'errno': RET.PARAMERR, 'errmsg': "请选择图片"})

        #  判断文件尾缀是否为图片
        if avatar.name.endswith(('.bmp', '.dib', '.png', '.jpg', '.jpeg', '.pbm', '.pgm', '.ppm', '.tif', '.tiff')) is False:
            return http.JsonResponse({'errno': RET.PARAMERR, 'errmsg': "头像只能选择图片"})

        #  如果上传过头像, 先删除之前头像
        if request.user.avatar_url:
            deletes(request.user.avatar_url)

        #  上传图片
        avatar_url = upload_img(avatar)
        #  如果返回None  修改失败
        if avatar_url is None:
            return http.JsonResponse({'errno': RET.PARAMERR, 'errmsg': "参数错误"})

        try:  # 保存
            request.user.avatar_url = avatar_url
            request.user.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'errno': RET.IOERR, 'errmsg': "保存失败"})
        return http.JsonResponse({"errno": "0", "errmsg": "OK", "data": avatar_url})



class AuthProfile(LoginRequiredJSONMixin, View):
    '''用户真实信息获取和设置'''

    def get(self, request):
        # 取到当前登录用户
        user = request.user

        # 获取当前用户的认证信息
        auth_dict = {
            "real_name": user.real_name,
            "id_card": user.id_card
        }
        # 返回信息
        return http.JsonResponse({'errno': RET.OK, 'errmsg': "OK", 'data': auth_dict})

    def post(self, request):

        # 取到当前登录用户
        user = request.user

        # 取到传过来的认证的信息
        data_dict = json.loads(request.body.decode())
        real_name = data_dict.get("real_name")
        id_card = data_dict.get("id_card")

        # 判断姓名是否符合正则
        if not re.match('^[\u4e00-\u9fa5]{2,6}$', real_name):
            return http.JsonResponse({'errno': RET.DBERR, 'errmsg': "请输入正确的姓名"})

        # 验证身份证信息是否合法
        if checkIdcard(id_card)!="验证通过!":
            return http.JsonResponse({'errno': RET.DBERR, 'errmsg': "请输入正确的身份证信息"})
        try:
            User.objects.get(id_card=id_card)
        except Exception as e:

            # 更新用户的认证信息
            user.real_name = real_name
            user.id_card = id_card
            try:
                user.save()
            except Exception as e:
                return http.JsonResponse({'errno': RET.DBERR, 'errmsg': "保存失败"})

        # 返回结果
            return http.JsonResponse({'errno': RET.OK, 'errmsg': "OK"})
        return http.JsonResponse({'errno': RET.DBERR, 'errmsg': "此身份证已被注册"})
